package cn.tedu.micro.demo.rabbitmq;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

@Slf4j
public class MyDirectProducer {
    private Channel channel;
    @Before
    public void createChannel() {
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("192.168.8.100");
            factory.setPort(5672);
            factory.setUsername("admin");
            factory.setPassword("123456");
            Connection connection = factory.newConnection();
            channel = connection.createChannel();
        } catch (Exception e) {
            log.error("创建通道失败");
        }
    }
    @Test
    public void declareBinding() {
        try {
//            声明2个队列
            channel.queueDeclare("queue01", true, false, false, null);
            channel.queueDeclare("queue02", true, false, false, null);
//            声明自定义路由交换机
            channel.exchangeDeclare("direct_ex","direct");
//            将声明的队列绑定给交换机
            channel.queueBind("queue01","direct_ex","北京");
            channel.queueBind("queue02","direct_ex","上海");
        } catch (Exception e) {
            log.error("创建队列失败");
        }
    }
    @Test
    public void sendMessage() {
        try {
//            1.准备消息
            String message = "hello rabbitmq 你好,我是王翠花";
            byte[] bytes = message.getBytes();
            channel.basicPublish("direct_ex","北京",null,bytes);
            log.info("发送消息成功");
        } catch (Exception e) {
            log.error("发送消息失败");
        }
    }
}
